<?
	session_start();
	
	function GetConnection()
	{
		return new mysqli('wyvern.cs.newpaltz.edu', 'N02036842', 's741780', 'N02036842_db');
	}
	//*********************************************************
	function GetCurrentUser()
	{
		$userId=$_SESSION['UserId'];
		$conn = GetConnection();
		$result = $conn->query("SELECT * FROM Accounts WHERE id=$userId");
		if($conn->error != null) return null;
		$rs = $result->fetch_assoc();
		$conn->close();
		return $rs;
	}
	//*********************************************************
	function Login($email, $password)
	{
		$conn = GetConnection();
		$result = $conn->query("SELECT id, Email, Password FROM Accounts WHERE Email='$email'");
		if($conn->error != null) return array(Email => 'Invalid Email');
		$rs = $result->fetch_assoc();
		if(!$rs)return array(Email => 'No Such User');
		$conn->close();
		if($rs['Password'] != $password) return array(Password => 'Incorect Password');
		
		$_SESSION['UserId'] = $rs['id'];
		return null;
	}
	//*********************************************************
	function SetNewAccount($rs)
	{
		$conn = GetConnection();
		$sql = "INSERT INTO Accounts (created_at, FirstName, LastName, Email, Password) VALUES (NOW(), '$rs[FirstName]', '$rs[LastName]', '$rs[Email]', '$rs[Password]')";
		$conn->query($sql);
		$error = $conn->error;	
		$conn->close();
		if( $error != '' ){
			//throw new Exception("Error:\nsql=$sql\nerror message\n$error");
			echo(print_r($error));
		}
	}
	
			//$result = $conn->query("SELECT U.id, U.Password FROM Users U JOIN ContactMethods CM ON U.id=CM.UserId WHERE CM.Value='$email'");